package edu.jkd.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.Session;
import edu.jkd.entity.Customer;
import edu.jkd.entity.Product;
import edu.jkd.service.ICustomerService;
import edu.jkd.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IProductService productService;

    /**
     * 登录界面验证，成功后查询首页所需数据，并跳转到首页
     * @param name
     * @param pwd
     * @param request
     * @return
     */
    @GetMapping("/login")
    public ModelAndView getById(String name, String pwd,boolean ok ,HttpServletRequest request,HttpServletResponse response){

        LambdaQueryWrapper<Customer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getCustName,name).eq(Customer::getCustPwd,pwd);
        Customer one = customerService.getOne(queryWrapper);
        ModelAndView mav=new ModelAndView();
        if(one !=null){
            System.out.println("存session");
            request.getSession().setAttribute("user",one);
            //实现记住密码的功能
            remember(ok,response, request.getSession());
            //调用service查询
            List<Product> productList = productService.list();
            //数据绑定
            mav.addObject("productList",productList);
            //页面跳转
            mav.setViewName("index");
            return mav;
        }else {
            mav.addObject("msg","用户名或密码错误");
        }
        mav.setViewName("login");
        return mav;
    }

    /**
     * 修改个人信息
     * @param json
     * @param request
     * @param response
     * @return
     */
    @PostMapping()
    public ModelAndView update(@RequestBody String json, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
        System.out.println(json);
        int title1 = json.indexOf("title");
        int temp1 = json.indexOf("&", title1);
        String substring = json.substring(title1 + 6, temp1);
        int i = json.indexOf("password");
        int temp2 = json.indexOf("&", i);
        String password = json.substring(i + 9, temp2);
        String decode = URLDecoder.decode(substring);
        LambdaQueryWrapper<Customer> queryWrapper=new LambdaQueryWrapper<>();
        Customer c1=(Customer) request.getSession().getAttribute("user");
        queryWrapper.eq(Customer::getCustName,c1.getCustName());
        Customer one = customerService.getOne(queryWrapper);
        one.setCustName(decode);
        one.setCustPwd(password);
        customerService.update(one,queryWrapper);
        //
        String custName = one.getCustName();
        session.setAttribute("user",one);

       //
        ModelAndView mav=new ModelAndView();
        mav.addObject("user",one);
        mav.setViewName("personal_Information");
        return mav;
    }
    /**
     * 注册账号,昵称不允许重复
     * @param name
     * @param pwd
     */
    @GetMapping("/sign")
    public void  save(String name,String pwd,HttpServletRequest request,HttpServletResponse response){
        Customer customer=new Customer();
        customer.setCustName(name);
        customer.setCustPwd(pwd);
        LambdaQueryWrapper<Customer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getCustName,name);
        Customer one = customerService.getOne(queryWrapper);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            response.setCharacterEncoding("utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(one !=null){
            out.print("<script>alert('Duplicate user name!'); window.location='../login.jsp'</script>");
        }else {
            customerService.save(customer);
            out.print("<script>alert('success!'); window.location='../login.jsp'</script>");
        }
        out.flush();
        out.close();
    }
    /**
     *退出登录
     * */
    @GetMapping("/loginout")
    public ModelAndView loginOut(HttpServletResponse response,HttpSession session){
        ModelAndView mov=new ModelAndView();
        //销毁session
        session.invalidate();
        mov.setViewName("login");
        return mov;
    }

    /**
     * 记住密码
     * @param ok
     * @param
     * @param response
     * @param session
     */

    public void remember(boolean ok,HttpServletResponse response, HttpSession session){
        System.out.println("存cookie");
        //记住
        if (ok){
            Customer user = (Customer)session.getAttribute("user");
            Cookie cookie1 = new Cookie("name", user.getCustName());
            Cookie cookie2 = new Cookie("pwd", user.getCustPwd());
            cookie1.setMaxAge(10*24*60*60);
            cookie2.setMaxAge(10*24*60*60);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }
        return;
    }


}
